package cn.yotta.user.core.server.iface.common.impl;

import cn.yotta.user.core.server.iface.common.CaptchaGenerator;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author wyaoyao
 * @date 2022/11/9 10:28
 * 使用Google Kaptcha 工具包生成图片验证码
 */
@Slf4j
public class DefaultCaptchaGenerator implements CaptchaGenerator {

    private final DefaultKaptcha defaultKaptcha;

    private final Integer expireSecond;



    public DefaultCaptchaGenerator(DefaultKaptcha defaultKaptcha, Integer expireSecond) {
        this.defaultKaptcha = defaultKaptcha;
        this.expireSecond = expireSecond;
    }

    @Override
    public Captcha generateCaptcha() {
        final String text = defaultKaptcha.createText();
        final BufferedImage image = defaultKaptcha.createImage(text);
        byte[] imageBytes = null;
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(5000)){
            ImageIO.write(image, "png", byteArrayOutputStream);
            imageBytes = byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Captcha.builder()
                .imageUrl("data:image/png;base64," + Base64.encode(imageBytes))
                .expireTime(expireSecond)
                .text(text).build();
    }


}
